package com.lxq.blog.com.lxq.blog.security;

import com.lxq.blog.com.lxq.blog.enums.RoleEnum;
import com.lxq.blog.com.lxq.blog.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

@Configuration
public class UserSecurity extends WebSecurityConfigurerAdapter {

    @Autowired
    UserService userService;
    @Autowired
    LoginSuccessHandler loginSuccessHandler;
    @Autowired
    LoginFailureHandler loginFailureHandler;

    @Bean
    PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder(10);
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //auth.inMemoryAuthentication().withUser("lxq").password("24166").roles("final");
        auth.userDetailsService(userService);
        //auth.authenticationProvider(provider);
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder(10));
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/admin/**")
                .hasAuthority(RoleEnum.ADMIN.getRole())
                .antMatchers("/user/**", "/userzone/**")
                .hasAuthority(RoleEnum.ORDINARY.getRole())
                .anyRequest().permitAll()
                .and()
                .formLogin().loginPage("/login.html").loginProcessingUrl("/login")
                .usernameParameter("username").passwordParameter("password")
                .successHandler(loginSuccessHandler)
                .failureHandler(loginFailureHandler)
                .and().csrf().disable()
                .logout().logoutUrl("/logout").invalidateHttpSession(true).clearAuthentication(true);
    }
}
